package com.asiainfo.complier.action;

import com.asiainfo.complier.conf.SysSetting;
import com.asiainfo.complier.helper.FileHelper;
import com.asiainfo.complier.helper.StringHelper;

import java.io.File;

public class JavaRunAction {

	/**
	 * get classpath
	 * 
	 * @return
	 */
	public String getClassPath(String extendClassPath) {
		String custPath = SysSetting.CUSTOMER_CLASS_PATH;
		String jdkPath = SysSetting.JDK_CLASS_PATH;
		if (extendClassPath != null)
			return String.format("-classpath \"%s;%s;%s\"", custPath, jdkPath,
					extendClassPath);
		else
			return String.format("-classpath \"%s;%s\"", custPath, jdkPath);

	}

	private String getApplicationName(String packages, String appName) {
		if (StringHelper.isNullOrEmpty(packages))
			return appName;
		else {
			return packages + "." + appName;
		}

	}

	/**
	 * @param filePath
	 * @param packages
	 * @return
	 */
	public String getRunCmd(String filePath, String packages) {
		String javacHome = SysSetting.JDK_PATH + File.separator + "bin"
				+ File.separator + "java";
		String appName = FileHelper.getFileNameWithoutExtName(filePath);
		String packetPath = getPacketPath(packages);
		String baseFilePath = filePath.replace(packetPath, "");
		return String.format("%s %s %s", javacHome, getClassPath(baseFilePath
				+ ";" + SysSetting.OUTPUT_PATH),
				getApplicationName(packages, appName));
	}

	/**
	 * @param packages
	 * @return
	 */
	private String getPacketPath(String packages) {
		if (StringHelper.isNullOrEmpty(packages))
			return "";

		String path = File.separator;
		path += packages.replace(".", File.separator);
		return path;
	}

	/**
	 * get output path
	 * 
	 * @return
	 */
	public String getOutputPath(String packages) {
		String path = getPacketPath(packages);
		String dir = String.format("-d \"%s\"", SysSetting.OUTPUT_PATH);

		File dirPath = new File(String.format("%s%s", SysSetting.OUTPUT_PATH,
				path));
		if (!dirPath.exists())
			dirPath.mkdirs();
		return dir;
	}

	/**
	 * ComplierCmd
	 * 
	 * @param filePath
	 * @param packages
	 * @return
	 */
	public String getComplierCmd(String filePath, String packages) {
		String javacHome = SysSetting.JDK_PATH + File.separator + "bin"
				+ File.separator + "javac";
		String packetPath = getPacketPath(packages);
		int index = filePath.indexOf(packetPath);
		if (index != -1)
			packetPath = filePath.substring(0, index);
		String baseFilePath = packetPath;
		return String.format("%s %s %s \"%s\"", javacHome,
				getClassPath(baseFilePath), getOutputPath(packages), filePath);

	}
}
